<?php


namespace app\api\logic;


use app\admin\controller\system\Config;
use app\common\model\WeChat;
use app\common\server\WeChatServer;
use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Factory;
use think\Controller;
use think\Db;
use app\api\server;
use think\facade\Cache;

class WeChatLogic extends Controller
{
    protected $APPID;
    protected $APPSECRET;
    protected $WXCONFIG;

    /**
     * 获取 AccessToken
     */
    public function getAccessToken()
    {
        $config = WeChatServer::getOaConfig();
        $this->APPID = $config['app_id'];
        $this->APPSECRET = $config['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->APPID . "&secret=" . $this->APPSECRET;
        $file_path = ROOT_PATH . DS . "wxtxt" . DS . "access_token.txt"; // ROOT_PATH . "public" .
        // 先判断 access_token 文件里的token是否过期，没过期继续使用，过期就更新
        $data = json_decode(self::get_php_file($file_path), true);

        // 过期 更新
        if (empty($data) || $data->expire_time < time()) {

            $res = server\CurlServer::send_post($url);

            $access_token = $res['access_token'];
            if ($access_token) {
                // 在当前时间戳的基础上加7000s (两小时)
                $data['expire_time'] = time() + 7000;
                $data['access_token'] = $res['access_token'];
                self::set_php_file($file_path, json_encode($data));
            }
        } else {
            // 未过期 直接使用
            $access_token = $data->access_token;
        }

        return $access_token;
    }


    // 获取存储文件中的token
    private static function get_php_file($filename)
    {
        if (is_dir($filename) || @mkdir($filename, 0777, true)) {
            return trim(($filename));
        };
        return false;
    }

    // 把token 存储到文件中
    private static function set_php_file($filename, $content)
    {
        $fp = fopen($filename, "w");
        fwrite($fp, $content);
        fclose($fp);
    }

    public function pushMessage($open_id)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->getAccessToken();
    }


    /**
     * 入口
     * 生成二维码
     */
    public function getQrcode()
    {
        $token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $token;

        // 参数
        $param = array();
        $param['action_name'] = "QR_SCENE";
        $param['action_info'] = array('scene' => array('scene_id' => '1122'));
        $param = json_encode($param);

        // 返回二维码的ticket和二维码图片解析地址
        $res = server\CurlServer::send_post($url, 'post', 'json', $param);

        // 通过ticket换取二维码
        $qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $res['ticket'];
        session($res['ticket'], "");
        $data = [
            "ticket" => $res['ticket'],
            "qrcode" => $qrcode
        ];
        return $data;
    }

    /**
     * 获取用户微信信息
     * @param $open_id
     * @param $ticket
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWxUser($open_id, $ticket)
    {
        $check = Db::name("user")
            ->field("id,disable")
            ->where("open_id", $open_id)
            ->find();

        if ($check) {
            if ($check['disable'] == 1) {
                //$check['token'] = server\JwtCheck::getJwtToken($check);
                $sess['disable'] = 1;
                Cache::set($ticket, json_encode($sess), 3600);
            } else {
                $user_info = LoginLogic::getUserInfo($check['id']);
                $user_info['token'] = server\JwtCheck::getJwtToken($user_info);
                session("user_info" . $check['id'], $user_info);
                Cache::set($ticket, json_encode($user_info), 3600);
            }
        } else {
            $access_token = $this->getAccessToken();
            $check_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $open_id . "&lang=zh_CN";
            $wx_user = file_get_contents($check_url);
            $wx_user = json_decode($wx_user, true);

            $send_data = [
                "open_id" => $wx_user['openid'],
                "nickname" => $wx_user['nickname'],
                "sex" => $wx_user['sex'],
                "city" => $wx_user['city'],
                "province" => $wx_user['province'],
                "country" => $wx_user['country'],
                "headimgurl" => $wx_user['headimgurl'],
                "subscribe_time" => $wx_user['subscribe_time'],
                "remark" => $wx_user['remark'],
                "subscribe_scene" => $wx_user['subscribe_scene']
            ];
            Cache::set($ticket, json_encode($send_data), 3600);
        }

        return true;
    }


    /**
     * 回复@todo
     * @return Text
     */
    public function reply()
    {
        $reply_content = Db::name('wechat_reply')
            ->where(['reply_type' => \app\common\model\WeChat::msg_event_subscribe, 'status' => 1, 'del' => 0])
            ->value('content');
        //关注回复空的话，找默认回复
        if (empty($reply_content)) {
            $reply_content = Db::name('wechat_reply')
                ->where(['reply_type' => \app\common\model\WeChat::msg_type_default, 'status' => 1, 'del' => 0])
                ->value('content');
        }
        if ($reply_content) {
            $text = new Text($reply_content);
            return $text;
        }
    }

    /**
     * 获取微信配置
     * @param $url
     * @return array|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function jsConfig($url)
    {
        $config = WeChatServer::getOaConfig();
        $app = Factory::officialAccount($config);
        $url = urldecode($url);
        $app->jssdk->setUrl($url);
        $apis = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'openLocation', 'getLocation', 'chooseWXPay', 'updateAppMessageShareData', 'updateTimelineShareData', 'openAddress'];
        try {
            $data = $app->jssdk->getConfigArray($apis, $debug = false, $beta = false);
            return data_success('', $data);
        } catch (Exception $e) {
            return data_error('公众号配置出错' . $e->getMessage());
        }
    }

    public function setMenu()
    {
        $token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $token;
        $menu_arr = [
            "button" => [
                [
                    "type" => "view",
                    "name" => "公司简介",
                    "url" => "https://mp.weixin.qq.com/s/BpqrI75qdxXBcwuoUeNzZQ"
                ],
                [
                    "name" => "商家入口",
                    "sub_button" => [
                        [
                            "type" => "click",
                            "name" => "搜索",
                            "key" => "V1001_GOOD"
                        ], [
                            "type" => "click",
                            "name" => "商家入驻",
                            "key" => "V1001_GOOD1"
                        ]
                    ],
                ]
            ],

        ];
        $res = server\CurlServer::send_post($url, 'post', 'json', json_encode($menu_arr, JSON_UNESCAPED_UNICODE));
        if ($res['errcode'] == 0 && $res['errmsg'] == "ok") {
            return true;
        }
        return false;
    }

//    public static function index()
//    {
//        //微信配置
//        $config = WeChatServer::getOaConfig();
//        $app = Factory::officialAccount($config);
//
//        $app->server->push(function ($message) {
//            switch ($message['MsgType']) {
//                case WeChat::msg_type_event: //关注事件
//                    switch ($message['Event']) {
//                        case WeChat::msg_event_subscribe:
//                            $reply_content = Db::name('wechat_reply')
//                                ->where(['reply_type' => WeChat::msg_event_subscribe, 'status' => 1, 'del' => 0])
//                                ->value('content');
//                            //关注回复空的话，找默认回复
//                            if (empty($reply_content)) {
//                                $reply_content = Db::name('wechat_reply')
//                                    ->where(['reply_type' => WeChat::msg_type_default, 'status' => 1, 'del' => 0])
//                                    ->value('content');
//                            }
//                            if ($reply_content) {
//                                $text = new Text($reply_content);
//                                return $text;
//                            }
//                            break;
//
//                    }
//
//                case WeChat::msg_type_text://消息类型
//                    $reply_list = Db::name('wechat_reply')
//                        ->where(['reply_type' => WeChat::msg_type_text, 'status' => 1, 'del' => 0])
//                        ->order('sort asc')
//                        ->select();
//                    $reply_content = '';
//                    foreach ($reply_list as $reply) {
//                        switch ($reply['matching_type']) {
//                            case 1://全匹配
//                                $reply['keyword'] === $message['Content'] && $reply_content = $reply['content'];
//                                break;
//                            case 2://模糊匹配
//                                stripos($reply['keyword'], $message['Content']) && $reply_content = $reply['content'];
//                                break;
//                        }
//                    }
//                    //消息回复为空的话，找默认回复
//                    if (empty($reply_content)) {
//                        $reply_content = Db::name('wechat_reply')
//                            ->where(['reply_type' => WeChat::msg_type_default, 'status' => 1, 'del' => 0])
//                            ->value('content');
//                    }
//                    if ($reply_content) {
//                        $text = new Text($reply_content);
//                        return $text;
//                    }
//                    break;
//
//
//            }
//        });
//        $response = $app->server->serve();
//        $response->send();
//
//    }

}